#include <iostream>

#include "sdlvideoviewer.h"

void SDLVideoViewer::Boot(string URL) {
    SDL_VERSION(&m_syswminfo.version);
    if (SDL_GetWMInfo(&m_syswminfo) <= 0 ||
            m_syswminfo.subsystem != SDL_SYSWM_X11) {
        throw exception();
    }
    m_x = 0;
    m_y = 0;
    m_width = 352;
    m_height = 288;
    m_engine->SetURL(URL);
    m_engine->Init();
    SetWindowLink(m_x, m_y, m_width, m_height);
    m_engine->Play();
}

SDLVideoViewer::~SDLVideoViewer() {

}

void SDLVideoViewer::Render() {

}

void SDLVideoViewer::SetSize(int width, int height) {
    m_syswminfo.info.x11.lock_func();
    XResizeWindow(m_syswminfo.info.x11.display, m_window, width, height);
    m_syswminfo.info.x11.unlock_func();
    m_width = width;
    m_height = height;
}

void SDLVideoViewer::SetPosition(int x, int y) {
    m_syswminfo.info.x11.lock_func();
    XMoveWindow(m_syswminfo.info.x11.display, m_window, x, y);
    m_syswminfo.info.x11.unlock_func();
    m_x = x;
    m_y = y;
}

bool SDLVideoViewer::CreateX11SubWindow(Display *dpy, Window parent,
        int x, int y, int width, int height) {
    Window win;
    int black;

    if (!dpy)
        return false;

    black = BlackPixel(dpy, DefaultScreen(dpy));
    win = XCreateSimpleWindow(dpy, parent, x, y, width, height,
            0, black, black);

    if (!win)
        return false;

    if (!XSelectInput(dpy, win, StructureNotifyMask))
        return 0;

    if (!XMapWindow(dpy, win))
        return false;

    while (1) {
        XEvent e;
        XNextEvent(dpy, &e);
        if (e.type == MapNotify && e.xmap.window == win)
            break;
    }

    XSelectInput(dpy, win, KeyPressMask | KeyReleaseMask);

    m_window = win;
    return true;
}

void SDLVideoViewer::SetWindowLink(int x, int y, int width, int height) {
    if (!m_syswminfo.version.major)
        return;

    m_syswminfo.info.x11.lock_func();

    CreateX11SubWindow(m_syswminfo.info.x11.display, m_syswminfo.info.x11.window,
            x, y, width, height);

    m_syswminfo.info.x11.unlock_func();

    m_engine->LinkToX11Window(m_window);
}
